package com.eco.fanliapp.admin.controller.web;
import com.eco.fanliapp.common.constant.NewsEnumLog;
import com.eco.fanliapp.common.response.ServerResponse;
import com.eco.fanliapp.dao.AppUserOrderMapper;
import com.eco.fanliapp.dao.SyDoubletwelveUserMapper;
import com.eco.fanliapp.entity.AppUser;
import com.eco.fanliapp.entity.SyDoubletwelveUser;
import com.eco.fanliapp.service.*;
import com.eco.fanliapp.utils.BigDecimalUtils;
import com.eco.fanliapp.utils.EasyPoiStyleUtils;
import com.eco.fanliapp.utils.EasyPoiUtils;
import com.eco.fanliapp.utils.StringUtils;
import com.eco.fanliapp.vo.DoubleElevenUserVo;
import com.eco.fanliapp.vo.DoubleTwelveUserVo;
import io.lettuce.core.dynamic.domain.Timeout;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.math.BigDecimal;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.TimeUnit;

/**
 * @date 2019-11-08
 */
@Controller
@RequestMapping("/web/activity")
public class DoubleElevenController{
    private static final Logger log = LoggerFactory.getLogger(DoubleElevenController.class);

    @Autowired
    private AppUserOrderMapper appUserOrderMapper;

    @Autowired
    private IAppUserService iAppUserService;

    @Autowired
    private ISyUserMoneyLogService syUserMoneyLogService;

    @Autowired
    private IAppNewsLogService iAppNewsLogService;

    @Autowired
    private RedisLockService redisLockService;

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private SyDoubletwelveUserMapper syDoubletwelveUserMapper;
    /**
     * 双十一导入
     * @return
     */
    @RequestMapping(value = "/doubleEleven/import")
    @ResponseBody
    public ServerResponse doubleElevenImport(HttpServletResponse response, MultipartFile file){
        Date dateTime = new Date();
        DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date lineDate = null;
        try {
             lineDate = dateFormat.parse("2019-12-31 18:00:00");//接口失效时间
        }catch (Exception e){}

        List<DoubleElevenUserVo> listBack = new ArrayList<>();
        if(lineDate == null){
            return ServerResponse.createBySuccess("你不是我的菜");
        }else if(lineDate.compareTo(dateTime) > 0) {
            try {
                List<DoubleElevenUserVo> list = EasyPoiUtils.importExcel(file, 1, 1, DoubleElevenUserVo.class);
                if (list != null && list.size() > 0) {
                    for (DoubleElevenUserVo deUserVo:list
                         ) {
                        //redis锁-时间
                        long startTimes = System.currentTimeMillis() + 1000 * 3600 * 2400;

                        //获取锁
                        if (!redisLockService.lock(deUserVo.getUserId() + "doubleElevenAddUserMoney" , startTimes + "")) {
                            log.info("活动奖励，用户Id={}，时间={}", deUserVo.getUserId(), new Date());
                            deUserVo.setStatusDesc("失败，已发放"+deUserVo.getIncentiveMoney());
                            listBack.add(deUserVo);
                            continue;
                        }
                        if(deUserVo != null && deUserVo.getUserId() != null && deUserVo.getIncentiveMoney() != null){

                            //通过用户id查询user ，加钱
                            AppUser appUser = iAppUserService.selectAppUserByUserId(deUserVo.getUserId());
                            if(appUser != null){
                                //用户不为空，加钱
                                int ii = iAppUserService.updateAppUseraddbalance(deUserVo.getUserId(), BigDecimalUtils.Format(deUserVo.getIncentiveMoney()));
                                log.info("双十一奖励 {}==用户id{}==金额{}", ii, deUserVo.getUserId(), deUserVo.getIncentiveMoney());
                                if(ii >0){
                                    iAppNewsLogService.newsType(deUserVo.getUserId(),
                                            NewsEnumLog.NEWS_AWARD_ACTIVITY.getNewsType(),
                                            BigDecimalUtils.Format(deUserVo.getIncentiveMoney()), deUserVo.getIncentiveMoney().toString());
                                    deUserVo.setStatusDesc("成功，金额{}"+deUserVo.getIncentiveMoney());
                                    listBack.add(deUserVo);
                                    //增加log日志
                                    syUserMoneyLogService.addSyUserMoneyLog(deUserVo.getUserId(), appUser.getBalance(), BigDecimalUtils.Format(deUserVo.getIncentiveMoney()), "双十一活动奖励", 2, 0);
                                }else {
                                    deUserVo.setStatusDesc("失败，金额{}"+deUserVo.getIncentiveMoney());
                                    listBack.add(deUserVo);
                                }
                            }else {
                                deUserVo.setStatusDesc("加钱失败，没有找到该用户");
                                listBack.add(deUserVo);
                            }
                        }else {
                            deUserVo.setStatusDesc("加钱失败，没有找到该用户或者奖励为空");
                            listBack.add(deUserVo);
                        }
                    }
                }
            }catch (Exception e){}

            EasyPoiUtils.exportExcel(listBack, "双十一活动", "双十一活动", DoubleElevenUserVo.class, EasyPoiStyleUtils.class, "doubleEleven.xls", response);
        }else {
            return null;
        }
        return null;
    }

    /**
     * 双十一导出
     * @return
     */
    @RequestMapping(value = "/doubleEleven/download")
    @ResponseBody
    public ServerResponse doubleElevenDownload(HttpServletResponse response ,Integer type,Long starTime, Long endTime){
       //导出符合条件的用户 0,全部，1（50-80）,2（80-150）,3（150以上）
        //1,查询出用户佣金满足条件的用户
        List<DoubleElevenUserVo> list =  appUserOrderMapper.selectDoubleElevenUser(type,starTime,endTime);

        if(list == null || list.size() == 0){
            return ServerResponse.createByErrorMessage("没有满足条件的用户");
        }

        for (DoubleElevenUserVo deUserVo:list
        ) {
            if(type == 1){
                deUserVo.setIncentiveMoney(new BigDecimal("8.88"));
            }else if(type == 2){
                deUserVo.setIncentiveMoney(new BigDecimal("18.88"));
            }else if(type == 3){
                deUserVo.setIncentiveMoney(new BigDecimal("38.88"));
            }else if(type == 0){
                if(Double.valueOf(deUserVo.getSubsidizeMoney().toString()) >= 50 && Double.valueOf(deUserVo.getSubsidizeMoney().toString()) < 80){
                    deUserVo.setIncentiveMoney(new BigDecimal("8.88"));
                }else if(Double.valueOf(deUserVo.getSubsidizeMoney().toString()) >= 80 && Double.valueOf(deUserVo.getSubsidizeMoney().toString()) < 150){
                    deUserVo.setIncentiveMoney(new BigDecimal("18.88"));
                }else if(Double.valueOf(deUserVo.getSubsidizeMoney().toString()) > 150){
                    deUserVo.setIncentiveMoney(new BigDecimal("38.88"));
                }
            }
        }

        try{
            EasyPoiUtils.exportExcel(list, "双十一活动", "双十一活动", DoubleElevenUserVo.class, EasyPoiStyleUtils.class, "doubleEleven.xls", response);
        }catch (Exception e){
            return ServerResponse.createByErrorMessage("下载失败");
        }
        return ServerResponse.createBySuccessMessage("下载成功");
    }

    /**
     * 双十一导出
     * @return
     */
    @RequestMapping(value = "/doubleEleven/download2")
    @ResponseBody
    public ServerResponse doubleElevenDownload2(HttpServletResponse response ,Integer type){
        //导出符合条件的用户 0,全部，1（50-80）,2（80-150）,3（150以上）
        //1,查询出用户佣金满足条件的用户
        List<DoubleElevenUserVo> list =  appUserOrderMapper.selectDoubleElevenUser2(type);

        if(list == null || list.size() == 0){
            return ServerResponse.createByErrorMessage("没有满足条件的用户");
        }

        for (DoubleElevenUserVo deUserVo:list
        ) {
            if(type == 1){
                deUserVo.setIncentiveMoney(new BigDecimal("8.88"));
            }else if(type == 2){
                deUserVo.setIncentiveMoney(new BigDecimal("18.88"));
            }else if(type == 3){
                deUserVo.setIncentiveMoney(new BigDecimal("38.88"));
            }else if(type == 0){
                if(Double.valueOf(deUserVo.getSubsidizeMoney().toString()) >= 50 && Double.valueOf(deUserVo.getSubsidizeMoney().toString()) < 80){
                    deUserVo.setIncentiveMoney(new BigDecimal("8.88"));
                }else if(Double.valueOf(deUserVo.getSubsidizeMoney().toString()) >= 80 && Double.valueOf(deUserVo.getSubsidizeMoney().toString()) < 150){
                    deUserVo.setIncentiveMoney(new BigDecimal("18.88"));
                }else if(Double.valueOf(deUserVo.getSubsidizeMoney().toString()) > 150){
                    deUserVo.setIncentiveMoney(new BigDecimal("38.88"));
                }
            }
        }

        try{
            EasyPoiUtils.exportExcel(list, "双十一活动", "双十一活动", DoubleElevenUserVo.class, EasyPoiStyleUtils.class, "doubleEleven.xls", response);
        }catch (Exception e){
            return ServerResponse.createByErrorMessage("下载失败");
        }
        return ServerResponse.createBySuccessMessage("下载成功");
    }


    /**
     *  //双十二抽奖
     *
     * @return
     */
    @RequestMapping(value = "/doubleTwelve/winList")
    @ResponseBody
    public ServerResponse doubleTwelveDownload(HttpServletResponse response, @RequestParam(defaultValue = "40")Integer number, @RequestParam(defaultValue = "1")Double minPrice, @RequestParam(defaultValue = "20")Double maxPrice, @RequestParam(defaultValue = "1576080000000")Long starTime, @RequestParam(defaultValue = "1576166400000")Long endTime) {
        //1,查询满足条件的用户
        List<DoubleTwelveUserVo> list = appUserOrderMapper.doubleTwelveDownload(minPrice,maxPrice,starTime,endTime);
        //随机抽 N 个
        Random rand = new Random();
        Map<String,DoubleTwelveUserVo> map = new HashMap<>();
        List<DoubleTwelveUserVo> userVoList = new ArrayList<>();
        int num = 0;

        if (list == null || list.size() < number) {
            try {
                EasyPoiUtils.exportExcel(list, "双十二活动", "活动中奖名单", DoubleTwelveUserVo.class, EasyPoiStyleUtils.class, "doubleTwelve.xls", response);
            } catch (Exception e) {
                return ServerResponse.createByErrorMessage("下载失败");
            }
            return ServerResponse.createByErrorMessage("满足条件的用户不足");
        }else if(list.size() >= number){

            while (num < number){
                int i = rand.nextInt(list.size());
                map.put(list.get(i).getUserId().toString(),list.get(i));
                num = map.size();
            }
        }
        if(map.size() == number){
            Set<String> keys = map.keySet();
            for (String userId:keys
            ) {
                DoubleTwelveUserVo dtVo =  map.get(userId);
                userVoList.add(dtVo);
            }
        }
        try {
            EasyPoiUtils.exportExcel(userVoList, "双十二活动", "活动中奖名单", DoubleTwelveUserVo.class, EasyPoiStyleUtils.class, "doubleTwelve.xls", response);
        } catch (Exception e) {
            return ServerResponse.createByErrorMessage("下载失败");
        }
        return ServerResponse.createBySuccessMessage("下载成功");
    }

    @RequestMapping(value = "/doubleTwelve/winListFalse")
    @ResponseBody
    public ServerResponse doubleTwelvewinListFalse(HttpServletResponse response,MultipartFile file){

        //1,查询满足条件的用户
        List<DoubleTwelveUserVo> list = appUserOrderMapper.doubleTwelveDownloadFalse();

        try {
            EasyPoiUtils.exportExcel(list, "双十二活动150", "活动中奖名单150", DoubleTwelveUserVo.class, EasyPoiStyleUtils.class, "doubleTwelveFalse.xls", response);

        }catch (Exception e){
            return ServerResponse.createByErrorMessage("下载失败");
        }

        return ServerResponse.createBySuccessMessage("下载成功");
    }

    @RequestMapping(value = "/doubleTwelve/import")
    @ResponseBody
    public ServerResponse doubleTwelveimport(HttpServletResponse response,MultipartFile file){

        List<DoubleTwelveUserVo> listT = new ArrayList<>();
        try {
            listT = EasyPoiUtils.importExcel(file, 1, 1, DoubleTwelveUserVo.class);

        }catch (Exception e){
            return ServerResponse.createByErrorMessage("上传失败");
        }
        //绑定订单
        for (DoubleTwelveUserVo vo:listT
        ) {
            if(vo != null){
               int i = syDoubletwelveUserMapper.updateByUserId(vo.getUserId(),vo.getOrderId(),vo.getFreeMoney());
                if(i > 0){
                    vo.setStatusDesc("成功");
                }else {
                    vo.setStatusDesc("失败");
                }
            }
        }
        EasyPoiUtils.exportExcel(listT, "双十二活动处理", "活动中奖名单", DoubleTwelveUserVo.class, EasyPoiStyleUtils.class, "doubleTwelve.xls", response);
        return ServerResponse.createBySuccessMessage("上传成功");
    }

}
